<template>
  <div :class="['message-input-toolbar', 'message-input-toolbar-h5', 'message-input-toolbar-uni']">
    <div v-if="isMyGroup" style="color: #c7c7c7; text-align: center; font-size: 12px">MyGroup</div>
    <div v-if="props.displayType === 'emojiPicker'">
      <EmojiPickerDialog />
    </div>
    <div v-else>
      <swiper :class="['message-input-toolbar-swiper']" :indicator-dots="isSwiperIndicatorDotsEnable" :autoplay="false"
        :circular="false">
        <swiper-item :class="[
    'message-input-toolbar-list',
    'message-input-toolbar-h5-list',
    'message-input-toolbar-uni-list',
  ]">
          <!-- <ImageUpload imageSourceType="camera" /> -->
          <!-- <ImageUpload imageSourceType="album" /> -->
          <!-- <VideoUpload videoSourceType="album" /> -->
          <!-- <VideoUpload videoSourceType="camera" /> -->
          <!-- <Evaluate
            v-if="currentExtensionList.length < 4"
            @onDialogPopupShowOrHide="handleSwiperDotShow"
          /> -->
          <!-- <Words
            v-if="currentExtensionList.length < 3"
            @onDialogPopupShowOrHide="handleSwiperDotShow"
          /> -->

          <!-- <template v-if="currentExtensionList[0]">
            <div v-for="(extension, index) in currentExtensionList.slice(0, 2)" :key="index">
              <ToolbarItemContainer
                v-if="
                  (extension &&
                    consultation.consultationMethod == '2' &&
                    genExtensionText(extension) == '语音通话') ||
                  (extension &&
                    consultation.consultationMethod == '3' &&
                    genExtensionText(extension) == '视频通话')
                "
                :iconFile="genExtensionIcon(extension)"
                :title="genExtensionText(extension)"
                iconWidth="25px"
                iconHeight="25px"
                :needDialog="false"
                @onIconClick="onExtensionClick(extension)"
              />
            </div>
          </template> -->

          <!-- 发送文件 -->
          <DFileBox />
          <!-- 语音通话 -->
          <ToolbarItemContainer v-if="consultation.consultationMethod == '2' || chatType == '会诊'"
            :iconFile="genExtensionIcon(voiceCall)" :title="genExtensionText(voiceCall)" iconWidth="25px"
            iconHeight="25px" :needDialog="false" @onIconClick="onExtensionClick(voiceCall)" />
          <!-- 视频通话 -->
          <ToolbarItemContainer v-if="consultation.consultationMethod == '3' || chatType == '会诊'"
            :iconFile="genExtensionIcon(videoCall)" :title="genExtensionText(videoCall)" iconWidth="25px"
            iconHeight="25px" :needDialog="false" @onIconClick="onExtensionClick(videoCall)" />
          <!-- 常用回复 -->
          <DWords />
          <!-- 问诊建议 -->
          <DSuggest v-if="chatType == '问诊'" />
          <!-- 整理病历 -->
          <DMedicalCase v-if="chatType == '问诊'" />
          <!-- 聊天记录 -->
          <DHistory />
          <!-- 会诊结论 -->
          <DConclusion v-if="chatType == '会诊'" :title="isMyGroup ? '会诊结论' : '会诊意见'" />
          <!-- 开具处方 -->
          <DPrescription v-if="isMyGroup" />
          <!-- 退回费用 -->
          <!-- <DRefund v-if="isMyGroup" /> -->
          <!-- 结束问诊 -->
          <DCloseConsultation v-if="isMyGroup" />
        </swiper-item>
        <!-- <swiper-item
          v-if="currentExtensionList[2] && currentExtensionList.length >= 3"
          :class="[
            'message-input-toolbar-list',
            'message-input-toolbar-h5-list',
            'message-input-toolbar-uni-list',
          ]"
        >
          <div v-for="(extension, index) in currentExtensionList.slice(4)" :key="index">
            <ToolbarItemContainer
              v-if="extension"
              :iconFile="genExtensionIcon(extension)"
              :title="genExtensionText(extension)"
              iconWidth="25px"
              iconHeight="25px"
              :needDialog="false"
              @onIconClick="onExtensionClick(extension)"
            />
          </div>
          <Evaluate
            v-if="currentExtensionList.length >= 4"
            @onDialogPopupShowOrHide="handleSwiperDotShow"
          />
          <Words
            v-if="currentExtensionList.length >= 3"
            @onDialogPopupShowOrHide="handleSwiperDotShow"
          />
        </swiper-item> -->
      </swiper>
    </div>
    <UserSelector ref="userSelectorRef" :type="selectorShowType" :currentConversation="currentConversation"
      :isGroup="isGroup" @submit="onUserSelectorSubmit" @cancel="onUserSelectorCancel" />
  </div>
</template>
<script setup lang="ts">
import { ref, onUnmounted, onMounted, computed } from '../../../adapter-vue'
import TUIChatEngine, {
  IConversationModel,
  TUIStore,
  StoreName,
} from '@tencentcloud/chat-uikit-engine'
import TUICore, { ExtensionInfo, TUIConstants } from '@tencentcloud/tui-core'
import ImageUpload from './image-upload/index.vue'
import VideoUpload from './video-upload/index.vue'
import Evaluate from './evaluate/index.vue'
import Words from './words/index.vue'
import FileUpload from './file-upload/index.vue'
import ToolbarItemContainer from './toolbar-item-container/index.vue'
import EmojiPickerDialog from './emoji-picker/emoji-picker-dialog.vue'
import UserSelector from './user-selector/index.vue'
import TUIChatConfig from '../config'
import { enableSampleTaskStatus } from '../../../utils/enableSampleTaskStatus'
import { ToolbarDisplayType } from '../../../interface'

// 自定义组件
import DFileBox from '@/TUIWidget/message-input-toolbar/d-fileBox/index.vue'
import DWords from '@/TUIWidget/message-input-toolbar/d-words/index.vue'
import DMedicalCase from '@/TUIWidget/message-input-toolbar/d-medical-case/index.vue'
import DRefund from '@/TUIWidget/message-input-toolbar/d-refund/index.vue'
import DCloseConsultation from '@/TUIWidget/message-input-toolbar/d-close-consultation/index.vue'
import DConclusion from '@/TUIWidget/message-input-toolbar/d-conclusion/index.vue'
import DPrescription from '@/TUIWidget/message-input-toolbar/d-prescription/index.vue'
import DHistory from '@/TUIWidget/message-input-toolbar/d-history/index.vue'
import DSuggest from '@/TUIWidget/message-input-toolbar/d-suggest/index.vue'

interface IProps {
  displayType: ToolbarDisplayType
}

const props = withDefaults(defineProps<IProps>(), {})

const currentConversation = ref<IConversationModel>()
const isGroup = ref<boolean>(false)
const selectorShowType = ref<string>('')
const userSelectorRef = ref()
const currentUserSelectorExtension = ref<ExtensionInfo | null>()
const currentExtensionList = ref<ExtensionInfo[]>([])
const isSwiperIndicatorDotsEnable = ref<boolean>(false)

const getExtensionList = (conversationID: string) => {
  if (!conversationID) {
    return
  }
  const chatType = TUIChatConfig.getChatType()
  const params: Record<string, boolean | string> = { chatType }
  // Backward compatibility: When callkit does not have chatType judgment, use filterVoice and filterVideo to filter
  if (chatType === TUIConstants.TUIChat.TYPE.CUSTOMER_SERVICE) {
    params.filterVoice = true
    params.filterVideo = true
    enableSampleTaskStatus('customerService')
  }
  // uni-app build ios app has null in last index need to filter
  currentExtensionList.value = [
    ...TUICore.getExtensionList(TUIConstants.TUIChat.EXTENSION.INPUT_MORE.EXT_ID, params),
  ].filter(extension => extension)
}

const onCurrentConversationUpdate = (conversation: IConversationModel) => {
  if (
    conversation?.conversationID &&
    conversation.conversationID !== currentConversation.value?.conversationID
  ) {
    getExtensionList(conversation.conversationID)
    if (currentExtensionList.value.length > 2) {
      // isSwiperIndicatorDotsEnable.value = true
    }
  }
  currentConversation.value = conversation
  isGroup.value = currentConversation?.value?.type === TUIChatEngine.TYPES.CONV_GROUP
}

onMounted(() => {
  TUIStore.watch(StoreName.CONV, {
    currentConversation: onCurrentConversationUpdate,
  })
})

onUnmounted(() => {
  TUIStore.unwatch(StoreName.CONV, {
    currentConversation: onCurrentConversationUpdate,
  })
})

// handle extensions onclick
const onExtensionClick = (extension: ExtensionInfo) => {
  // uniapp vue2 build wx lose listener proto
  const extensionModel = currentExtensionList.value.find(
    targetExtension => targetExtension?.data?.name === extension?.data?.name
  )
  switch (extensionModel?.data?.name) {
    case 'voiceCall':
      onCallExtensionClicked(extensionModel, 1)
      break
    case 'videoCall':
      onCallExtensionClicked(extensionModel, 2)
      break
    case 'search':
      extensionModel?.listener?.onClicked?.()
      break
    default:
      break
  }
}

const genOfflinePushInfo = () => {
  // doc: https://cloud.tencent.com/document/product/269/105713
  return {
    title: 'call',
    description: 'you have a call',
    androidSound: 'private_ring',
    iOSSound: '01.caf',
  }
}

const onCallExtensionClicked = (extension: ExtensionInfo, callType: number) => {
  selectorShowType.value = extension?.data?.name
  if (currentConversation?.value?.type === TUIChatEngine.TYPES.CONV_C2C) {
    extension?.listener?.onClicked?.({
      userIDList: [currentConversation?.value?.conversationID?.slice(3)],
      type: callType,
      callParams: {
        offlinePushInfo: genOfflinePushInfo(),
      },
    })
  } else if (isGroup.value) {
    currentUserSelectorExtension.value = extension
    userSelectorRef?.value?.toggleShow && userSelectorRef.value.toggleShow(true)
  }
}

const genExtensionIcon = (extension: any) => {
  return extension?.icon
}
const genExtensionText = (extension: any) => {
  return extension?.text
}

const onUserSelectorSubmit = (selectedInfo: any) => {
  currentUserSelectorExtension.value?.listener?.onClicked?.({
    ...selectedInfo,
    callParams: {
      offlinePushInfo: genOfflinePushInfo(),
    },
  })
  currentUserSelectorExtension.value = null
}

const onUserSelectorCancel = () => {
  currentUserSelectorExtension.value = null
}

const handleSwiperDotShow = (showStatus: boolean) => {
  isSwiperIndicatorDotsEnable.value = currentExtensionList.value.length > 2 ? !showStatus : false
}

// 获取自定义字段
const chatType = ref<string>('')
const consultation = ref<object>({})
const groupOwnerID = ref<string>('')
// UI 层监听当前更新通知
let onCurrentGroupUpdated = function (currentGroup) {
  if (!currentGroup?.groupCustomField) return

  // 设置会话自定义字段
  chatType.value = currentGroup.groupCustomField.find(
    (item: any) => item.key === 'diagnosis_type'
  ).value
  consultation.value = JSON.parse(
    currentGroup.groupCustomField.find((item: any) => item.key === 'consultation').value || 0
  )
  groupOwnerID.value = currentGroup.ownerID
}

// 监听当前会话ID更新
TUIStore.watch(StoreName.GRP, {
  currentGroup: onCurrentGroupUpdated,
})

const isMyGroup = computed(() => {
  return groupOwnerID.value === TUIChatEngine.userID
})

import voiceCallIcon from '@/TUIWidget/static/icon/phone.png'
const voiceCall = ref({
  weight: 1000,
  text: '语音通话',
  icon: voiceCallIcon,
  data: {
    name: 'voiceCall',
  },
  listener: {},
})
import videoCallIcon from '@/TUIWidget/static/icon/video.png'
const videoCall = ref({
  weight: 900,
  text: '视频通话',
  icon: videoCallIcon,
  data: {
    name: 'videoCall',
  },
  listener: {},
})
</script>
<script lang="ts">
export default {
  options: {
    styleIsolation: 'shared',
  },
}
</script>
<style lang="scss">
@import '../../../assets/styles/common';
@import './style/uni';
</style>
